var datagrid; //定义全局变量datagrid
var editRow = undefined; //定义全局变量：当前编辑的行
var precautionDelIds = [];//删除的防范措施的ids
var selectUserId ="";//人员选择input Id
$(function(){
    //加载部门树
    queryDepartmentTree();
    //  alert(CONSTANT.DictionaryTypeDefConstants.HD_REASON);
    //加载数据字典下拉列表
    queryDictionaryList("reason",CONSTANT.DictionaryTypeDefConstants.HD_REASON);//隐患原因
    queryDictionaryList("hdType",CONSTANT.DictionaryTypeDefConstants.HD_TYPE);//隐患分类
    queryDictionaryList("hdSource",CONSTANT.DictionaryTypeDefConstants.HD_SOURCE);//隐患分类
    queryDictionaryList("plate",CONSTANT.DictionaryTypeDefConstants.HD_PLATE);//所属板块
    queryDictionaryList("riskGrade",CONSTANT.DictionaryTypeDefConstants.HD_RISKGRADE);//隐患风险等级
    queryDictionaryList("hdGrade",CONSTANT.DictionaryTypeDefConstants.HD_HDGRADE);//所属板块
    queryDictionaryList("capitalSource",CONSTANT.DictionaryTypeDefConstants.CAPITALSOURCE);//资金来源
    //年度下拉列表
    queryYearthList("yearth");

    //加载防范措施列表数据
    var hdId = $("#hdId").val();
    datagrid = $("#precautionList").datagrid({
        url: ROOT_PATH+'/hiddenDanger/hdRegister/queryPrecautionList.shtml?hdId='+hdId, //请求的数据源
        iconCls: 'icon-save', //图标
        //pagination: true, //显示分页
        //pageSize: 3, //页大小
        //pageList: [3, 6, 9], //页大小下拉选项此项各value是pageSize的倍数
        rownumbers:true,
        singleSelect:true,
        fit: true, //datagrid自适应宽度
        fitColumns: true, //列自适应宽度
        striped: true, //行背景交换
        nowap: true, //列内容多时自动折至第二行
        //border: false,
        idField: 'id', //主键
        toolbar:'#tb',
        columns: [[//显示的列
            {field:'id',width:100,checkbox:true},
            //{field:'dutyUserId',width:100,hidden:true},
            {field:'dutyUserId',title:'责任人id',width:200,hidden:true,
                /*formatter:function (value,row,index) {
                 return row.dutyUserId
                 },*/
                editor:{type:'textbox',options:{
                }}
            },
            {field:'dutyUserName',title:'责任人',width:200,
              /*  formatter:function (value,row,index) {
                    return row.dutyUserName
                },*/
                editor:{type:'textbox',options:{
                    editable:false,
                    required:"true",
                    icons: [{
                        iconCls:'icon-add',
                        handler: function(e){
                            add_contractorInfo_func();
                            // alert(a);
                        }
                    }]
                    }}
            },
            {field:'measureContent',title:'措施内容',width:300, editor:{type:'textbox',
                options:{
                    required:"true",
                    multiline:true
                }}},
            {field:'startTime',title:'开始时间',width:200, editor:{type:'datebox',options:{
                required:'true',
                editable:false
            }}},
            {field:'endTime',title:'结束时间',width:200, editor:{type:'datebox',options:{
                required:'true',
                editable:false
            }}}
        ]],
        queryParams: {
            //action: 'query'
        }, //查询参数
        onAfterEdit: function (rowIndex, rowData, changes) {
            //endEdit该方法触发此事件
            // console.info(rowData);
            // var rows= datagrid.datagrid("getChanges");
            //console.log(rows);
            editRow = undefined;
        },
        onDblClickRow: function (rowIndex, rowData) {
            //双击开启编辑行
            if (editRow != undefined) {
                datagrid.datagrid("endEdit", editRow);
            }
            if (editRow == undefined) {
                datagrid.datagrid("beginEdit", rowIndex);
                editRow = rowIndex;
            }
        }
    });


    //保存按钮方法
    $('#btn_save').on("click", function () {
        if($(".hdRegisterForm").form('validate')&&$("#precautionForm").form('validate')){
            layer.confirm("确定保存？",{btn:['确定','取消']},function(){
                var layerIndex=parent.layer.getFrameIndex(window.name); //获取窗口索引
                //序列化表单数据
                var data = $(".hdRegisterForm").serializeArray();
                data.push({name:'precautionData',value:getPrecautionData()});
                data.push({name:'precautionDelIds',value:precautionDelIds});
                // console.log(getPrecautionData());
                $.ajax({
                    url:ROOT_PATH + '/hiddenDanger/hdRegister/edit.shtml',//提交地址
                    data:data,//将表单数据序列化
                    type:"POST",
                    dataType:"json",
                    success:function(result){
                        if (result.success){
                            layer.msg(result.message,{time:1000,icon:1},function(){
                                WindowManager.closeLayer({
                                    returnValue:""
                                });
                            });
                        }else{
                            layer.msg(result.message,{time:1000,icon:1},function(){
                                //parent.layer.close(layerIndex);
                            });
                        }
                    }
                });
            });
        }else{
            layer.msg("请按规则填写信息!",{time:1000,icon:2});
        }
    });
    /**
     * 绑定人员选择事件
     */
    $("#chargeUser").textbox({
        iconWidth: 15,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                selectUserId ="chargeUser";
                add_contractorInfo_func();
            }
        }]
    });
    $("#acceptUser").textbox({
        iconWidth: 15,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                selectUserId ="acceptUser";
                add_contractorInfo_func();
            }
        }]
    });



});
/**
 * 定义表单验证
 */
$.extend($.fn.validatebox.defaults.rules, {
    minLength: {
        validator: function(value, param){
            return value.length >= param[0];
        },
        message: '最小长度'
    },
    intOrFloat: {// 验证整数或小数
        validator: function (value) {
           // alert(/^\d+(\.\d+)?$/i.test(value));
            return /^\d+(\.\d+)?$/i.test(value);
        },
        message: '请输入数字，并确保格式正确'
    },
    validSelect:{//验证为空字符串
        validator:function(value){
            //alert(value!="请选择");
            return value!="请选择"&&value!='';
        },
        message:'请选择'
    }

});
/**
 * 查询部门树方法
 */
function queryDepartmentTree(){
    $.ajax({
        url:ROOT_PATH + '/permission/department/getDepartmentTree.shtml',//提交地址
        data:{parentId : 0},//将表单数据序列化
        type:"POST",
        dataType:"json",
        success:function(result){
            $('#dept').combotree(
                {
                    data:result,
                    loadFilter:function(data){
                        var newData = new Array();
                        newData.push({id:'',text:'请选择'});
                        newData.push(data[0]);
                        return newData;
                    }
                }
            );
            $("#dutyDept").combotree({
                data:result,
                loadFilter:function(data){
                    var newData = new Array();
                    newData.push({id:'',text:'请选择'});
                    newData.push(data[0]);
                    return newData;
                }
            });
            //主管部门
            $("#competentDept").combotree({
                data:result,
                loadFilter:function(data){
                    var newData = new Array();
                    newData.push({id:"",text:'请选择'});
                    newData.push(data[0]);
                    return newData;
                }
            });
        }
    });

}
/**
 * 人员信息选择
 */
/*var getSelectedUser = function (data) {
    if(selectUserId==""||selectUserId==null){
        var dutyUserED= datagrid.datagrid('getEditor', {index:editRow,field:'dutyUserName'});
        var dutyUserIdED= datagrid.datagrid('getEditor', {index:editRow,field:'dutyUserId'});
        $(dutyUserED.target).textbox("setValue",data[0].name)
        $(dutyUserIdED.target).textbox("setValue",data[0].id)
    }else{
        $("#"+selectUserId).textbox('setValue',data[0].name);
        $("#"+selectUserId+"Id").val(data[0].id);
        selectUserId = "";
    }
    // console.log(data);

   // $("#"+selectUserId).textbox('setText',data[0].name);

    // $("#"+selectUserId).textbox('setValue','值123');
    //$("#"+selectUserId).val(data.id);
    // $("#"+selectUserId).text(data.name);
    return data;
};*/
var add_contractorInfo_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack:function(data){
            if(selectUserId==""||selectUserId==null){
                var dutyUserED= datagrid.datagrid('getEditor', {index:editRow,field:'dutyUserName'});
                var dutyUserIdED= datagrid.datagrid('getEditor', {index:editRow,field:'dutyUserId'});
                $(dutyUserED.target).textbox("setValue",data[0].name)
                $(dutyUserIdED.target).textbox("setValue",data[0].id)
            }else{
                $("#"+selectUserId).textbox('setValue',data[0].name);
                $("#"+selectUserId+"Id").val(data[0].id);
                selectUserId = "";
            }
        }
    });
    /*layer.open({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0'
    });*/
};
/**
 * 查询数据字典列表的方法
 * @param id
 * @param code
 */
function queryDictionaryList(id,code){
    $.ajax({
        url:ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml',//提交地址
        data:{code : code},//将表单数据序列化
        type:"POST",
        dataType:"json",
        success:function(result){
            $('#'+id).combobox(
                {
                    data:result,
                    valueField:'id',
                    textField:'text',
                    loadFilter:function(data){
                        var newData = new Array();
                        newData.push({id:"",text:'请选择'});
                        for(var i=0;i<data.length;i++){
                            newData.push(data[i])
                        }
                        return newData;
                    }
                }
            );

        }
    });
}
/**
 * 设置年度下拉列表
 * @param id
 * @param code
 */
function queryYearthList(id){
    var date = new Date();
    var year = date.getFullYear();
    var yearthData = new Array();
    yearthData.push({id:"",text:"请选择"});
    for(var i =0;i<6;i++){
        var y = {id:year-i,text:(year-i)+'年'}
        yearthData.push(y);
    }
    $('#'+id).combobox(
        {
            data:yearthData,
            valueField:'id',
            textField:'text'
        }
    );

}
/**
 * 选择风险信息弹出框方法
 */
var add_riskLevelInfo_func = function () {
    var riskAssessPeople = $("#riskAssessPeople").textbox("getValue");
    var riskAssessMoney = $("#riskAssessMoney").textbox("getValue");
    var riskAssessEnvironment = $("#riskAssessEnvironment").textbox("getValue");
    var riskAssessPrestige = $("#riskAssessPrestige").textbox("getValue");
    var riskAssessMax = $("#riskAssessMax").textbox("getValue");
    /*var riskData = {};
    riskData.riskAssessPeople = riskAssessPeople;
    riskData.riskAssessMoney = riskAssessMoney;
    riskData.riskAssessEnvironment = riskAssessEnvironment;
    riskData.riskAssessPrestige = riskAssessPrestige;
    riskData.riskAssessMax = riskAssessMax;*/
    layer.open({
        type: 2,
        title: '选择风险信息信息',
        area: ['90%', '90%'],
        content: ROOT_PATH + "/risk/matrix/toMatrixPage.shtml?riskAssessPeople="+riskAssessPeople+
        "&riskAssessMoney="+riskAssessMoney+"&riskAssessEnvironment="+riskAssessEnvironment+
        "&riskAssessPrestige="+riskAssessPrestige +"&riskAssessMax="+riskAssessMax+"&isEdit=1"
    });
};
//操作传回的值
function getRiskAssessInfo(obj){
    $("#riskAssessMax").textbox("setValue",obj.riskAssessMax);
    $("#riskAssessPeople").textbox("setValue",obj.riskAssessPeople);
    $("#riskAssessMoney").textbox("setValue",obj.riskAssessMoney);
    $("#riskAssessEnvironment").textbox("setValue",obj.riskAssessEnvironment);
    $("#riskAssessPrestige").textbox("setValue",obj.riskAssessPrestige);
    $("#riskAssessUserId").val(loginUserId);
    $("#riskAssessUserName").textbox("setText",loginUserName);
}



/*==============================================================================*/
/**
 * 添加编辑行
 */
function appendTableRow() {//添加列表的操作按钮添加，修改，删除等
    //添加时先判断是否有开启编辑的行，如果有则把开户编辑的那行结束编辑
    if (editRow != undefined) {
        datagrid.datagrid("endEdit", editRow);
    }
    //添加时如果没有正在编辑的行，则在datagrid的第一行插入一行
    if (editRow == undefined) {
        datagrid.datagrid("insertRow", {
            index: 0, // index start with 0
            row: {

            }
        });
        //将新插入的那一行开启编辑状态
        datagrid.datagrid("beginEdit", 0);
        //给当前编辑的行赋值
        editRow = 0;
    }

}

/**
 * 删除行
 */
function deleteTableRow () {
    //删除时先获取选择行
    var rows = datagrid.datagrid("getSelections");
    //选择要删除的行
    if (rows.length > 0) {
        var index = layer.confirm("确定要删除吗？",{btn:["确定","取消"]},function(){
            //var ids = [];
            for (var i = 0; i < rows.length; i++) {
                precautionDelIds.push(rows[i].id);
            }
            var row= datagrid.datagrid("getSelected");
            var selectedIndex =  datagrid.datagrid('getRowIndex',row)
            datagrid.datagrid('deleteRow', selectedIndex);
            editRow=undefined;
            //将选择到的行存入数组并用,分隔转换成字符串，
            //本例只是前台操作没有与数据库进行交互所以此处只是弹出要传入后台的id
            //alert(ids.join(','));
            layer.close(index);
        });
        /*$.messager.confirm("提示", "你确定要删除吗?", function (r) {
            if (r) {

            }
        });*/
    }
    else {
        layer.alert( "请选择要删除的行");
    }
}

/**
 * 保存行数据
 */
function saveTableRow () {
    //保存时结束当前编辑的行，自动触发onAfterEdit事件如果要与后台交互可将数据通过Ajax提交后台
    datagrid.datagrid("endEdit", editRow);
}

/**
 * 编辑行数据
 */
function editTableRow() {
    //修改时要获取选择到的行
    var rows = datagrid.datagrid("getSelections");
    //如果只选择了一行则可以进行修改，否则不操作
    if (rows.length == 1) {
        //修改之前先关闭已经开启的编辑行，当调用endEdit该方法时会触发onAfterEdit事件
        if (editRow != undefined) {
            datagrid.datagrid("endEdit", editRow);
        }
        //当无编辑行时
        if (editRow == undefined) {
            //获取到当前选择行的下标
            var index = datagrid.datagrid("getRowIndex", rows[0]);
            //开启编辑
            datagrid.datagrid("beginEdit", index);
            //把当前开启编辑的行赋值给全局变量editRow
            editRow = index;
            //当开启了当前选择行的编辑状态之后，
            //应该取消当前列表的所有选择行，要不然双击之后无法再选择其他行进行编辑
            datagrid.datagrid("unselectAll");
        }
    }
}
/**
 * 取消编辑行
 */
function rejectTableRow () {
    var index =  layer.confirm("确定撤销将删除所有的编辑数据！",{btn:['确定','取消']},function(){
        //取消当前编辑行把当前编辑行罢undefined回滚改变的数据,取消选择的行
        //清楚删除的善举ids
        precautionDelIds = [];
        editRow = undefined;
        datagrid.datagrid("rejectChanges");
        datagrid.datagrid("unselectAll");
        layer.close(index);
    });

}
/**
 * 提交表格数据
 */
function getPrecautionData(){
    //保存表格编辑数据
    saveTableRow();
    //获取编辑表格数据
    var rows= datagrid.datagrid("getChanges");
    var str = JSON.stringify(rows);
    //var data = JSON.parse(str);
    //data.push("precautionDelIds",precautionDelIds);
    return str;
}